package com.gree.scmservice.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gree.common.exception.base.BaseException;
import com.gree.scmservice.controller.EchartController;
import com.gree.scmservice.service.ElasticSearchService;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.BucketOrder;
import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramInterval;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.joda.time.DateTimeZone;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * Created by 180686 on 2021/10/29 16:59
 */
@Service
public class ElasticSearchServiceImpl implements ElasticSearchService {

    @Autowired
    RestHighLevelClient restHighLevelClient;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public JSONArray queryScmMenuLog(EchartController.EchartVo echartVo) {
        String start = echartVo.getStart();
        String end = echartVo.getEnd();
        int displayNum = echartVo.getDisplayNum();

        JSONArray jsonArray;
        try {
            SearchRequest searchRequest = new SearchRequest("gscm-menu-**");
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("time")
                    .gte(start)
                    .lte(end)
                    .format("strict_date_optional_time"));
            sourceBuilder.query(boolQueryBuilder);
            sourceBuilder.aggregation(AggregationBuilders.terms("gscm-menu-**").field("tnam.keyword").order(BucketOrder.count(false)).size(displayNum));
            sourceBuilder.size(0);
            sourceBuilder.docValueField("@timestamp","date_time").docValueField("time","date_time");
            sourceBuilder.query(boolQueryBuilder);
            searchRequest.source(sourceBuilder);
            SearchResponse response;
            try {
                response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            } catch (IOException e) {
                throw new BaseException("异常");
            }
            jsonArray = JSONObject.parseObject(response.toString()).getJSONObject("aggregations").getJSONObject("sterms#gscm-menu-**").getJSONArray("buckets");
        }catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new BaseException("异常");
        }
        return jsonArray;
    }

    @Override
    public JSONArray fuzzyQuery() {
        return null;
    }

    @Override
    public JSONArray queryScmLoginLog(EchartController.EchartVo echartVo) {
        String start = echartVo.getStart();
        String end = echartVo.getEnd();
        String comp = echartVo.getComp();
        int displayNum = echartVo.getDisplayNum();

        JSONArray jsonArray;
        try {
            SearchRequest searchRequest = new SearchRequest("gscm-logininfo-**");
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

            boolQueryBuilder.filter(QueryBuilders.rangeQuery("login_time")
                    .gte(start)
                    .lte(end)
                    .format("strict_date_optional_time"))
                    .filter(QueryBuilders.matchPhraseQuery("comp", comp))
                    .filter(QueryBuilders.matchPhraseQuery("status", "0"))
                    .filter(QueryBuilders.matchPhraseQuery("msg.keyword", "登录成功"));
            sourceBuilder.query(boolQueryBuilder);
            sourceBuilder.aggregation(
                    AggregationBuilders.terms("comps").field("dsca.keyword").order(BucketOrder.count(false)).size(displayNum)
                            .subAggregation(AggregationBuilders.dateHistogram("times").field("login_time").dateHistogramInterval(DateHistogramInterval.DAY).timeZone(DateTimeZone.UTC)
                                    .subAggregation(AggregationBuilders.cardinality("login_names").field("login_name.keyword"))));
            sourceBuilder.size(0);
            sourceBuilder.docValueField("@timestamp", "date_time").docValueField("time", "date_time");
            sourceBuilder.query(boolQueryBuilder);
            searchRequest.source(sourceBuilder);
            SearchResponse response;
            try {
                response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            } catch (IOException e) {
                throw new BaseException("异常");
            }
            jsonArray = JSONObject.parseObject(response.toString()).getJSONObject("aggregations").getJSONObject("sterms#comps").getJSONArray("buckets");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new BaseException("异常");
        }
        return jsonArray;
    }

}
